package inits

import (
	"fmt"
	"github.com/redis/go-redis/v9"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"week_exam_2_3/global"
	"week_exam_2_3/internal/model"
)

func Init() {
	ConfRead()
	MysqlLink()
	RedisLink()
}

func RedisLink() {
	global.RDB = redis.NewClient(&redis.Options{
		Addr:     fmt.Sprintf("%s:%s", global.AppConfig.Redis.Host, global.AppConfig.Redis.Port),
		Password: global.AppConfig.Redis.Password,
		DB:       0,
	})
	err := global.RDB.Set(global.Ctx, "trys", "ok", 0).Err()
	if err != nil {
		panic(err)
	}
	fmt.Println("redis ok")
}

func MysqlLink() {
	var err error
	Dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local", global.AppConfig.Mysql.User, global.AppConfig.Mysql.Password, global.AppConfig.Mysql.Host, global.AppConfig.Mysql.Port, global.AppConfig.Mysql.Database)
	global.DB, err = gorm.Open(mysql.Open(Dsn))
	if err != nil {
		panic("failed to connect database")
	}
	if err = global.DB.AutoMigrate(&model.User{}, &model.Friend{}, &model.Chat{}); err != nil {
		panic("Mysql AutoMigrate error:" + err.Error())
	}
	fmt.Println("Mysql AutoMigrate success")
}

func ConfRead() {
	viper.SetConfigFile("../../conf/AppConf.yaml")
	viper.ReadInConfig()
	viper.Unmarshal(&global.AppConfig)
	fmt.Println("AppConf: ", global.AppConfig)
}
